package com.dixon.worddayday.service;

import com.dixon.worddayday.config.BusinessException;
import com.dixon.worddayday.dao.CustomerRepository;
import com.dixon.worddayday.model.Customer;
import com.dixon.worddayday.request.RegisterReq;
import com.dixon.worddayday.response.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public BaseRes register(RegisterReq registerReq) {
        String username = registerReq.getUsername().trim();
        String password = registerReq.getPassword().trim();

        if("admin".equals(username)) {
            throw new BusinessException("非法账户名！");
        }

        Customer exist = customerRepository.findByName(username);
        if(exist != null) {
            throw new BusinessException("账户已存在！");
        }

        Customer customer = new Customer();
        customer.setName(username);
        customer.setPassword(passwordEncoder.encode(password));
        customer.setCreateTime(LocalDateTime.now());

        customerRepository.save(customer);

        return BaseRes.success();
    }


}
